package com.primaryedu.ui;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.bean.BannerBean;
import com.primaryedu.bean.VersionBean;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.manager.ActivityManager;
import com.primaryedu.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import okhttp3.Call;

/**
 * 启动页面
 *
 * @author jun.wang
 * @description
 * @data 2016年12月12日
 */
@SuppressLint("NewApi")
public class LoadActivity extends BaseActivity {
    ActivityManager activityManager;

    private final int UPDATA_CLIENT = 1001;
    private final int GET_UNDATAINFO_ERROR = 1002;
    private final int DOWN_ERROR = 1003;
    private VersionBean versionBean;

    private Handler handler = new Handler() {

        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 101:
                    uplate();
                    break;

                case UPDATA_CLIENT:
                    //对话框通知用户升级程序
                    showUpdataDialog();
                    break;
                case GET_UNDATAINFO_ERROR:
                    //服务器超时
                    Toast.makeText(getApplicationContext(), "获取服务器更新信息失败", 1).show();
                    break;
                case DOWN_ERROR:
                    //下载apk失败
                    Toast.makeText(getApplicationContext(), "下载新版本失败", 1).show();
                    break;

                case 1005:
//	    	    showToast("当前是最新版本！");
                    loadToMain();
                    break;

                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.TRANSPARENT);
        }

//        setContentView(R.layout.activity_load);

        activityManager = ActivityManager.getInstance();
        setParamter();

//        handler.postDelayed(new Runnable() {
//			
//			@Override
//			public void run() {
//				// 判断是否登录过
//				if(TextUtils.isEmpty(GlobalData.getUserId(LoadActivity.this)) ||
//						GlobalData.getUserId(LoadActivity.this).equals("-1")){
//					 Intent intent = new Intent(LoadActivity.this , LoginActivity.class) ;
//					 startActivity(intent);
//					 finish();
//				}else {
////					 GlobalData.saveFirst(LoadActivity.this, "1");
//					 activityManager.pushActivity(LoadActivity.this);
//					 Intent intent = new Intent(LoadActivity.this , MainActivity.class) ;
//					 intent.putExtra("index", "1") ;
//					 startActivity(intent);
//					 finish();
//				 }
//			}
//		}, 2000) ;	

        checkVersion();
    }

    @Override
    protected int BindLayout() {
        return R.layout.activity_load;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    /*************************************************
     * 获取屏幕的宽度和高度
     */
    private void setParamter() {
        DisplayMetrics metrics = this.getApplicationContext().getResources().getDisplayMetrics();

        int heightPixels = metrics.heightPixels;
        int widthPixels = metrics.widthPixels;
        GlobalData.heightPixels = heightPixels;
        GlobalData.widthPixels = widthPixels;
        System.out.println("屏幕的宽度:" + heightPixels);
        System.out.println("屏幕的高度:" + widthPixels);
    }

    private void checkVersion() {
      /*  OkHttpUtils.get()//
                .url(Contants.getVersion)
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println("response==" + response);
                        try {
                            JSONObject json = new JSONObject(response);
                            if (response != null && !"".equals(response)) {
                                String reason = json.getString("reason");
                                int result = json.getInt("result");
                                String data = json.getString("data");

                                if (result == 1) {

                                    versionBean = new Gson().fromJson(data,
                                            new TypeToken<VersionBean>() {
                                            }.getType());
                                    System.out.println("versionBean==" + versionBean);
                                    handler.sendEmptyMessage(101);
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });*/
        StringBuilder builder = new StringBuilder();
        builder.append(Contants.getVersion);

        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                builder.toString(), new Response.Listener<String>() {

            @Override
            public void onResponse(String arg0) {
                System.out.println("arg0==" + arg0);
                try {
                    JSONObject json = new JSONObject(arg0);
                    if (arg0 != null && !"".equals(arg0)) {
                        String reason = json.getString("reason");
                        int result = json.getInt("result");
                        String data = json.getString("data");

                        if (result == 1) {

                            versionBean = new Gson().fromJson(data,
                                    new TypeToken<VersionBean>() {
                                    }.getType());
                            System.out.println("versionBean==" + versionBean);
                            handler.sendEmptyMessage(101);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
	            showToast("检查更新失败！") ;
                handler.sendEmptyMessage(1005);
            }
        });
        //为此get请求设置一个Tag属性
        stringRequest.setTag("GET_TAG");
        //将此get请求加入
        requestQueue.add(stringRequest);

    }

    private void uplate() {

        try {
            float version = Float.parseFloat(versionBean.getVersionCode());
            float current = Float.parseFloat(Utils.getVersionCode(LoadActivity.this));

            if (version > current) {
                handler.sendEmptyMessage(UPDATA_CLIENT);
            } else {
                handler.sendEmptyMessage(1005);
            }

        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        }
    }

    /*
    *
    *  弹出对话框通知用户更新程序
    *  弹出对话框的步骤：
    *  1.创建alertDialog的builder.
    *  2.要给builder设置属性, 对话框的内容,样式,按钮
    *  3.通过builder 创建一个对话框
    *  4.对话框show()出来
    */
    protected void showUpdataDialog() {
        AlertDialog.Builder builer = new Builder(LoadActivity.this);
        builer.setTitle("版本升级");
        builer.setMessage(versionBean.getDescription());
        //当点确定按钮时从服务器上下载 新的apk 然后安装
        builer.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                downLoadApk();
            }
        });

        //当点取消按钮时进行登录
        builer.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                loadToMain();
            }
        });
        AlertDialog dialog = builer.create();
        dialog.show();
    }

    /*
     * 从服务器中下载APK
     */
    protected void downLoadApk() {
        final ProgressDialog pd;    //进度条对话框
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.show();
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = Utils.getFileFromServer(versionBean.getApkUrlNet(), pd);
                    sleep(3000);
                    installApk(file);
                    pd.dismiss(); //结束掉进度条对话框
                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = DOWN_ERROR;
                    handler.sendMessage(msg);
                    e.printStackTrace();
                }
            }
        }.start();
    }

    //安装apk
    protected void installApk(File file) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //执行的数据类型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }

    private void loadToMain() {
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                // 判断是否登录过
                if (TextUtils.isEmpty(GlobalData.getUserId(LoadActivity.this)) ||
                        GlobalData.getUserId(LoadActivity.this).equals("-1")) {
                    Intent intent = new Intent(LoadActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    activityManager.pushActivity(LoadActivity.this);
                    Intent intent = new Intent(LoadActivity.this, MainActivity.class);
                    intent.putExtra("index", "1");
                    startActivity(intent);
                    finish();
                }
            }
        }, 1000);
    }

    ;

}
